-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
73 lines (57 loc) · 1.4 KB
/
Solution.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
Node(int value) : data(value), next(nullptr) {}
};
void printList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
cout << "NULL" << endl;
}
Node* removeNthFromEnd(Node* head, int n) {
Node* dummy = new Node(0);
dummy->next = head;
Node *fast = dummy, *slow = dummy;
for (int i = 0; i <= n; i++) {
if (fast) fast = fast->next;
}
while (fast) {
fast = fast->next;
slow = slow->next;
}
Node* toDelete = slow->next;
slow->next = toDelete->next;
delete toDelete;
Node* newHead = dummy->next;
delete dummy;
return newHead;
}
int main() {
int n, value, pos;
cout << "Enter the number of nodes: ";
cin >> n;
Node *head = nullptr, *tail = nullptr;
for (int i = 0; i < n; i++) {
cout << "Enter value for node " << i + 1 << ": ";
cin >> value;
Node* newNode = new Node(value);
if (!head) {
head = tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
cout << "Enter the position from the end to remove: ";
cin >> pos;
cout << "Original List: ";
printList(head);
head = removeNthFromEnd(head, pos);
cout << "Updated List: ";
printList(head);
return 0;
}